package com.personal.oa.service;

import com.personal.oa.dao.OADao;
import com.personal.oa.repository.EBDocSolrRepository;
import com.personal.oa.solr.EBDocSolrModel;
import com.personal.oa.until.Unitl;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.util.*;

/**
 * Created by Administrator on 2017/9/13.
 */
@Service
public class EBServerImpl implements EBServer {

    private static final Logger logger = LoggerFactory.getLogger(EBServerImpl.class.getName());

    //因为查询数据的mysql语句一样，不做更改
    @Autowired
    private OADao oADao;

    @Autowired
    private EBDocSolrRepository eBDocSolrRepository;

    private EBDocSolrModel eBDocSolrModel;

    private List<EBDocSolrModel> oadsms = new ArrayList<>();

    @Value("${num}")
    private int num;

    //oai
    List<String> oais;
    //creator
    List<String> creators;
    //subject
    List<String> subjects;
    //webaddress
    List<String> webaddresss;
    //doi
    List<String> dois;

    //language
    List<String> languages;
    //languagecn
//    List<String> languagescn;

    //isbn
    List<String> isbns;
    //issn
    List<String> issns;
    //KEYWORD
    List<String> keywords;

    /**
     * 将mysql数据转到solr字段
     *
     * @param startNum 开始条数
     * @param terminationNum 终止条数
     */
    @Override
    public void insertMysqlFromSolrDoc(Integer startNum, Integer terminationNum) throws FileNotFoundException {

        //记录当前的对象uuid
        String ouuid = "st";
        //记录description
        String description = null;
        //记录开始数
        int sn = startNum;
        //记录结束数
        int en = startNum+num;

        //提前清空一下，保证solr库中的都是新数据
//        oADocSolrRepository.deleteAll();
        Map<String,String> las = new HashMap<>();//Unitl().DataMatchTransformation("language");
        //语言的中英文比照存储
        //Map<String,String> lascn = DataMatchTransformation("languagecn");

        while (true) {
            logger.warn("从编号:"+sn+"到"+en);
            //取出指定条数的info
            long checkdbstart = System.currentTimeMillis();
            List<Map<String, Object>> ls = oADao.findSpecifiedStrip(sn, en);
            long checkdbend = System.currentTimeMillis();
            logger.warn("查询数据耗时:"+(checkdbend-checkdbstart));
            logger.warn("开始处理数据......");

            for (Map<String, Object> oa : ls) {
                //数据库中的字段UUID
                String fielduid = oa.get("tfuuid").toString();
                //数据库中的对象uuid
                String dbouuid = oa.get("obuuid").toString();
                //数据库中的内容字段
                String con = oa.get("te_content").toString();
                //数据库中的类型字段
                String typefiled = oa.get("tb_typeid").toString();

                if (!ouuid.equals(dbouuid)) {//对象ID不等的时候继续
                    if (!"st".equals(ouuid)) {//对象ID不等于初始化的时候继续
                        eBDocSolrModel.setOai(oais);
                        eBDocSolrModel.setCreator(creators);
                        eBDocSolrModel.setSubject(subjects);
                        eBDocSolrModel.setDescription(description);
                        description = null;
                        eBDocSolrModel.setWebaddress(webaddresss);
                        eBDocSolrModel.setDoi(dois);
                        eBDocSolrModel.setLanguage(languages);
//                        oADocSolrModel.setLanguagecn(languagescn);

                        eBDocSolrModel.setIsbn(isbns);
                        eBDocSolrModel.setIssn(issns);
                        eBDocSolrModel.setKetwords(keywords);

                        //加入对象类型
                        eBDocSolrModel.setOatypecn(typefiled);

                        oadsms.add(eBDocSolrModel);
                    }

                    ouuid = dbouuid;
                    eBDocSolrModel = new EBDocSolrModel();
                    //加入对象id
                    eBDocSolrModel.setId(dbouuid);

                    oais = new ArrayList<>();
                    creators = new ArrayList<>();
                    subjects = new ArrayList<>();
                    webaddresss = new ArrayList<>();
                    dois = new ArrayList<>();

                    languages = new ArrayList<>();
//                    languagescn = new ArrayList<>();

                    isbns = new ArrayList<>();
                    issns = new ArrayList<>();
                    keywords = new ArrayList<>();

                }

                switch (fielduid) {
                    //oai
                    case "e37bd41d-8df2-11e7-9753-1c1b0d1cb748":
                        if (con.startsWith("oai:")) {
                            oais.add(con.substring(4));
                        }else {
                            oais.add(con);
                        }
                        break;
                    //datestamp 更新时间
                    case "06f092fd-8df3-11e7-9753-1c1b0d1cb748":
                        Date dtc = new Unitl().convertDate(con, dbouuid, logger);
                        if(dtc!=null){
                            eBDocSolrModel.setDatestamp(dtc);
                            //datestampyear
                            eBDocSolrModel.setDatestampyear(dtc.getYear()+1900);
                        }
                        break;
                    //title 标题
                    case "51bd9b54-8df4-11e7-9753-1c1b0d1cb748":
                        eBDocSolrModel.setTitle(StringEscapeUtils.unescapeHtml4(con));
                        break;
                    //creator 作者
                    case "56245e05-8df4-11e7-9753-1c1b0d1cb748":
                        creators.add(con);
                        break;
                    //subject 学科
                    case "5a767d35-8df4-11e7-9753-1c1b0d1cb748":
                        subjects.add(con);
                        break;
                    //description 描述
                    case "5ea386c7-8df4-11e7-9753-1c1b0d1cb748":
                        if (description==null) {
                            description = StringEscapeUtils.unescapeHtml4(con);
                        } else {
                            description = description + StringEscapeUtils.unescapeHtml4(con);
                        }
                        break;
                    //creattime 创建时间
                    case "642bf276-8df4-11e7-9753-1c1b0d1cb748":
                        Date ctc = new Unitl().convertDate(con, dbouuid, logger);
                        if(ctc!=null){
                            if(ctc.before(new Date())){//表示ctc小于当期时间
                                eBDocSolrModel.setCreattime(ctc);
                                //creattimeyear
                                eBDocSolrModel.setCreattimeyear(ctc.getYear()+1900);
                            }
                        }
                        break;
                    //type 类型(不是oa的分类)
                    case "685b95b6-8df4-11e7-9753-1c1b0d1cb748":
                        eBDocSolrModel.setType(con);
                        break;
                    //webaddress 网址
                    case "6d8fcfb8-8df4-11e7-9753-1c1b0d1cb748":
                        webaddresss.add(StringEscapeUtils.unescapeHtml4(con));
                        break;
                    //doi
                    case "77ab2c86-8df4-11e7-9753-1c1b0d1cb748":
                        if (con.startsWith("doi:")) {
                            dois.add(con.substring(4));
                        }else {
                            dois.add(con);
                        }
                        break;
                    //publisher 出版社
                    case "e0f5da25-9781-11e7-aea2-1c1b0d1cb748":
                        eBDocSolrModel.setPublisher(con);
                        break;
                    //language 语言
                    case "f16d02d9-9781-11e7-aea2-1c1b0d1cb748":
                        boolean lc = true;
                        for(String str:las.keySet()){
                            if(con.indexOf(str)!=-1){
                                languages.add(las.get(str));
//                                languagescn.add(lascn.get(las.get(str)));
                                lc = false;
                            }
                        }
                        if(lc){
                            languages.add(las.get("other"));
//                            languagescn.add(lascn.get(las.get("other")));
                        }
                        break;
                    //ISBN
                    case "81f7c233-a25b-11e7-a865-1c1b0d1cb748":
                        isbns.add(con);
                        break;
                    //ISSN
                    case "ff8ba074-9781-11e7-aea2-1c1b0d1cb748":
                        issns.add(con);
                        break;
                    //KEYWORDS 关键词
                    case "71c9542c-a27a-11e7-a865-1c1b0d1cb748":
                        keywords.add(con);
                        break;

                }
            }
            logger.warn("结束处理数据......开始solr录入");
            eBDocSolrRepository.save(oadsms);
            logger.warn("结束solr录入\n");
            oadsms.clear();

            sn = en;
            en = en + num;
            //如何跳出循环
            if (sn == terminationNum) {
                break;
            }
        }
    }

}
